const jwt = require('jsonwebtoken')
const {
  NAME_OR_PASSWORD_IS_REQUIERD,
  NAMW_IS_NOT_EXISTS,
  PASSWORD_IS_INCORRENT,
  UNAUTHORIZATION,
  VOIDAUTHORIZATION
} = require("../config/error");
const {
  PUBLIC_KEY
} = require('../config/screct');
const userService = require("../service/user.service");
const md5Password = require("../utils/md5-password");

const verifyLogin = async (ctx, next) => {
  const {
    name,
    password
  } = ctx.request.body;
  //   判断用户名和密码是否为空
  if (!name || !password) {
    return ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIERD, ctx);
  }
  //   查询该用户是否在数据库
  const users = await userService.findUserName(name)
  const user = users[0]
  if (!user) {
    return ctx.app.emit('error', NAMW_IS_NOT_EXISTS, ctx)
  }
  // 判断数据库中用户与密码是否相匹配
  if (user.password !== md5Password(password)) {
    return ctx.app.emit('error', PASSWORD_IS_INCORRENT, ctx)
  }

  // 将拿到的user数据共享到ctx中
  ctx.user = user

  // 验证通过执行下一个中间件
  await next();
};

// 解析token中间件
const verifyAuth = async (ctx, next) => {
  // 获取token
  const authorization = ctx.headers.authorization //形式为  Bearer XXXX
  if (!authorization) {
    return ctx.app.emit('error', UNAUTHORIZATION, ctx)
  }
  const token = authorization.replace('Bearer ', '')
  // 验证token是否有效
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256']
    })
    // console.log(result);
    // 将token保存到ctx中以便使用
    ctx.user = result
    await next()
  } catch (error) {
    console.log(error);
    ctx.app.emit('error', VOIDAUTHORIZATION, ctx)
  }
}


module.exports = {
  verifyLogin,
  verifyAuth
}